package gov.mogaha.ntis.cmm.mob.servlet;

import gov.mogaha.ntis.cmm.mob.R;
import gov.mogaha.ntis.cmm.mob.util.Toaster;
import wire.client.HttpConnector;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;

public class CmmMobServletHandler {
	public static final int PROGRESS_DIALOG = 8000;
	public static final int CONN_START = 0;
	public static final int CONN_END = 1;
	public static final int CERT_ERROR = 3;
	Activity mActivity;
	public CmmMobServletHandler(Activity activity) {
		// TODO Auto-generated constructor stub
		mActivity = activity;
	}

	public Handler getHandler(final HttpResult result){
		Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				try {
					switch (msg.what) {
					case CONN_START:	//서버연결시작
						mActivity.showDialog(PROGRESS_DIALOG);
						break;
					case CONN_END:		//서버연결종료
						if (result != null) {
							result.httpCallback((CmmMobServlet.DataSet) msg.obj);
						}
						mActivity.dismissDialog(PROGRESS_DIALOG);
						mActivity.removeDialog(PROGRESS_DIALOG);
						break;
					case HttpConnector.CONNECT_ERROR:		//연결오류
						mActivity.dismissDialog(PROGRESS_DIALOG);
						mActivity.removeDialog(PROGRESS_DIALOG);
						Toaster.showMsg(mActivity, R.string.http_srv_err);
						break;
					case HttpConnector.SEND_ERROR:		//패킷전송오류
						mActivity.dismissDialog(PROGRESS_DIALOG);
						mActivity.removeDialog(PROGRESS_DIALOG);
						Toaster.showMsg(mActivity, R.string.http_packetsend_err);
						break;
					case HttpConnector.RECEIVE_ERROR:		//패킷수신오류
						mActivity.dismissDialog(PROGRESS_DIALOG);
						mActivity.removeDialog(PROGRESS_DIALOG);
						Toaster.showMsg(mActivity, R.string.http_packetsend_err);
						break;
					case HttpConnector.ETC_ERROR:		//기타 오류
						mActivity.dismissDialog(PROGRESS_DIALOG);
						mActivity.removeDialog(PROGRESS_DIALOG);
						Toaster.showMsg(mActivity, R.string.http_etc_err);
						break;
					case CERT_ERROR:	//인증서에러
						Toaster.showMsg(mActivity, R.string.http_cert_err);
						mActivity.dismissDialog(PROGRESS_DIALOG);
						mActivity.removeDialog(PROGRESS_DIALOG);
						break;
					default:
						break;
					}
				} catch (Exception e) {
					e.getMessage();
					// TODO: handle exception
					try {
						mActivity.dismissDialog(PROGRESS_DIALOG);
						mActivity.removeDialog(PROGRESS_DIALOG);
					} catch (Exception e2) {
						// TODO: handle exception
						e2.getMessage();
					}
					//DialogError는 그냥 무시하고
					
				}
			}
		};
		return handler;
	}
	
	/**
	 * 통신 후 결과값을 리턴받기 위한 인터페이스이며 사용시에는 data.getData("key")를 사용
	 * @author itatech
	 *
	 */
	public static interface HttpResult {
		public void httpCallback(CmmMobServlet.DataSet data);
	}
}
